<template>
  <div>
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <div class="el-icon-search icon" />
        &nbsp;筛选查询
        <el-button @click="handleResetForm('searchForm')">重置</el-button>
        <el-button type="primary" @click="handleGetTableData(1)">查询</el-button>
        <el-button
          type="text"
          @click="swithSearchhandler"
        >
          <div v-show="!isShowSearch">
            <div class="el-icon-arrow-down" />
            <span>展开筛选</span>
          </div>
          <div v-show="isShowSearch">
            <div class="el-icon-arrow-up" />
            <span>收起筛选</span>
          </div>
        </el-button>
      </div>
      <el-form ref="searchForm" :model="searchForm" label-width="70px">
        <el-row :gutter="24">
          <el-col :span="6">
            <el-form-item label="行业类型" prop="industryTypes">
              <el-select
                filterable
                multiple
                collapse-tags
                clearable
                v-model="searchForm.industryTypes"
                placeholder="请选择"
                @change="(e) => handleUpdateModelData('T1', e)"
              >
                <el-option
                  v-for="item in industryTypeOptions"
                  :key="item.modelNo"
                  :label="item.modelName"
                  :value="item.modelNo"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="一级模块" prop="modelOneNos">
              <el-select
                filterable
                multiple
                collapse-tags
                clearable
                v-model="searchForm.modelOneNos"
                placeholder="请选择"
                @change="(e) => handleUpdateModelData('M1', e)"
              >
                <el-option
                  v-for="item in modelOneNosOptions"
                  :key="item.modelNo"
                  :label="item.modelName"
                  :value="item.modelNo"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="二级模块" prop="modelTwoNos">
              <el-select
                filterable
                multiple
                collapse-tags
                clearable
                v-model="searchForm.modelTwoNos"
                placeholder="请选择"
                @change="(e) => handleUpdateModelData('M2', e)"
              >
                <el-option
                  v-for="item in modelTwoNosOptions"
                  :key="item.modelNo"
                  :label="item.modelName"
                  :value="item.modelNo"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="三级模块" prop="modelThreeNos">
              <el-select
                filterable
                multiple
                collapse-tags
                clearable
                v-model="searchForm.modelThreeNos"
                placeholder="请选择"
                @change="(e) => handleUpdateModelData('M3', e)"
              >
                <el-option
                  v-for="item in modelThreeNosOptions"
                  :key="item.modelNo"
                  :label="item.modelName"
                  :value="item.modelNo"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24" v-show="isShowSearch">
          <el-col :span="6">
            <el-form-item label="四级模块" prop="modelFourNos">
              <el-select
                filterable
                multiple
                collapse-tags
                clearable
                v-model="searchForm.modelFourNos"
                placeholder="请选择"
              >
                <el-option
                  v-for="item in modelFourNosOptions"
                  :key="item.modelNo"
                  :label="item.modelName"
                  :value="item.modelNo"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="一级分类" prop="categoryOneNos">
              <el-select
                filterable
                multiple
                collapse-tags
                clearable
                v-model="searchForm.categoryOneNos"
                placeholder="请选择"
                @change="(e) => handleUpdateModelData('C1', e)"
              >
                <el-option
                  v-for="item in categoryOneNosOptions"
                  :key="item.categoryNo"
                  :label="item.categoryName"
                  :value="item.categoryNo"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="二级分类" prop="categoryTwoNos">
              <el-select
                filterable
                multiple
                collapse-tags
                clearable
                v-model="searchForm.categoryTwoNos"
                placeholder="请选择"
                @change="(e) => handleUpdateModelData('C2', e)"
              >
                <el-option
                  v-for="item in categoryTwoNosOptions"
                  :key="item.categoryNo"
                  :label="item.categoryName"
                  :value="item.categoryNo"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="三级分类" prop="categoryThreeNos">
              <el-select
                filterable
                multiple
                collapse-tags
                clearable
                v-model="searchForm.categoryThreeNos"
                placeholder="请选择"
                @change="(e) => handleUpdateModelData('C3', e)"
              >
                <el-option
                  v-for="item in categoryThreeNosOptions"
                  :key="item.categoryNo"
                  :label="item.categoryName"
                  :value="item.categoryNo"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="四级分类" prop="categoryFourNos">
              <el-select
                filterable
                multiple
                collapse-tags
                clearable
                v-model="searchForm.categoryFourNos"
                placeholder="请选择"
              >
                <el-option
                  v-for="item in categoryFourNosOptions"
                  :key="item.categoryNo"
                  :label="item.categoryName"
                  :value="item.categoryNo"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="管理中心" prop="deptCenters">
              <el-select
                filterable
                multiple
                collapse-tags
                clearable
                v-model="searchForm.deptCenters"
                placeholder="请选择"
              >
                <el-option
                  v-for="(item, index) in deptCentersOptions"
                  :key="index"
                  :label="item"
                  :value="item"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-card>
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span> 数据列表</span>
        <el-button type="primary" @click="handleExport" :loading="exportLoading">导出</el-button>
      </div>
      <basic-table
        showPagination
        :columns="columns"
        :loading="tableLoading"
        :dataSource="tableData"
        :pagination="pagination"
        :total="pagination.total"
        @pageChange="handlePageChange"
        @pageSizeSelect="handlePageSizeChange"
      >
      </basic-table>
    </el-card>
  </div>
</template>
<script>
import { ApiRequest, ApiRequestExportTable } from '@api/basePage';
import BasicTable from '@/components/skusTable';
import { isResponseSuccess } from '@/utils/bizUtils';
import { MODULE_COLUMNS } from '../consonts';
import { handleFlatTreeData } from '../utils';
export default {
  components: {
    BasicTable
  },
  data () {
    return {
      isShowSearch: false,
      tableLoading: false,
      exportLoading: false,
      searchForm: {
        industryTypes: [],
        modelOneNos: [],
        modelTwoNos: [],
        modelThreeNos: [],
        modelFourNos: [],
        categoryOneNos: [],
        categoryTwoNos: [],
        categoryThreeNos: [],
        categoryFourNos: [],
        deptCenters: [] // 管理中心
      },
      industryTypeOptions: [], // 行业类型全集
      modelOneNosAllOptions: [], // 一级模块下拉集合全集
      modelTwoNosAllOptions: [], // 二级模块下拉集合全集
      modelThreeNosAllOptions: [], // 三级模块下拉集合全集
      modelFourNosAllOptions: [], // 四级模块下拉集合全集
      categoryOneNosOptions: [], // 一级分类下拉集合
      categoryTwoNosOptions: [], // 二级分类下拉集合
      categoryThreeNosOptions: [], // 三级分类下拉集合
      categoryFourNosOptions: [], // 四级分类下拉集合
      deptCentersOptions: [], // 管理中心集合
      pagination: {
        pageNum: 1, // 当前页码
        pageSize: 50, // 每页条数
        total: 0
      },
      tableData: [],
      columns: MODULE_COLUMNS,
      modelData: []
    };
  },
  computed: {
    // 一级模块下拉选项集合
    modelOneNosOptions () {
      return this.filterMoudleData(
        this.modelOneNosAllOptions,
        this.searchForm.industryTypes,
        'parentModelNo'
      );
    },
    // 二级模块下拉选项集合
    modelTwoNosOptions () {
      return this.filterMoudleData(
        this.modelTwoNosAllOptions,
        this.searchForm.modelOneNos,
        'parentModelNo'
      );
    },
    // 三级模块下拉选项集合
    modelThreeNosOptions () {
      return this.filterMoudleData(
        this.modelThreeNosAllOptions,
        this.searchForm.modelTwoNos,
        'parentModelNo'
      );
    },
    // 四级模块下拉选项集合
    modelFourNosOptions () {
      return this.filterMoudleData(
        this.modelFourNosAllOptions,
        this.searchForm.modelThreeNos,
        'parentModelNo'
      );
    }
  },
  created () {
    // 获取行业类型及模块数据
    this.getModelTreeDataAction();
    // 获取管理中心数据
    this.getAllDeptCenterDataAction();
    // 获取一级分类数据集合
    this.getCategoryDataAction('C0', ['systemUuid']);
  },
  mounted () {},
  methods: {
    // 展开收起开关
    swithSearchhandler () {
      this.isShowSearch = !this.isShowSearch;
    },
    /* 获取表格数据action */
    getTableDataAction (data) {
      this.tableLoading = true;
      ApiRequest('/sysback/product/model/getProductModelCategoryRel', 'post', data)
        .then((res) => {
          this.tableLoading = false;
          if (!isResponseSuccess(res)) {
            this.tableData = [];
            this.pagination.total = 0;
            return false;
          }
          let { results, totalNum, nowPage, pageShow } = res.retData;
          for (let i = 0; i < results.length; i++) {
            results[i].serNum = i + (nowPage - 1) * (pageShow) + 1;
          }
          this.tableData = results;
          this.pagination.total = totalNum;
        })
        .catch(() => {
          this.tableLoading = false;
        });
    },
    /* 获取模块数据action */
    getModelTreeDataAction (data = {}) {
      ApiRequest('/sysback/product/model/getProductModelTree', 'get', data)
        .then((res) => {
          if (isResponseSuccess(res)) {
            this.formatMoudleData(res.retData);
          }
        })
        .catch(() => {
        });
    },
    /* 获取管理中心数据action */
    getAllDeptCenterDataAction (data) {
      ApiRequest('/sysback/product/model/getAllDeptCenter', 'get', data).then((res) => {
        if (isResponseSuccess(res)) {
          this.deptCentersOptions = res.retData || [];
        }
      });
    },
    /* 获取品类数据action */
    getCategoryDataAction (level, data = []) {
      if (data.length === 0) {
        return false;
      }
      ApiRequest('/sysback/choose/category/getByParentUuids', 'post', data).then(
        (res) => {
          if (isResponseSuccess(res)) {
            const result = res.retData || [];
            if (level == 'C0') {
              this.categoryOneNosOptions = result;
            }
            if (level == 'C1') {
              this.categoryTwoNosOptions = result;
            }
            if (level == 'C2') {
              this.categoryThreeNosOptions = result;
            }
            if (level == 'C3') {
              this.categoryFourNosOptions = result;
            }
          }
        }
      );
    },
    // 表单重置
    handleResetForm (formName) {
      this.$nextTick(() => {
        this.$refs[formName].resetFields();
      });
    },
    // 模块数据级联操作清空已选项
    handleUpdateModelData (level, e) {
      if (level == 'T1') {
        this.searchForm.modelOneNos = [];
        this.searchForm.modelTwoNos = [];
        this.searchForm.modelThreeNos = [];
        this.searchForm.modelFourNos = [];
      }
      if (level == 'M1') {
        this.searchForm.modelTwoNos = [];
        this.searchForm.modelThreeNos = [];
        this.searchForm.modelFourNos = [];
      }
      if (level == 'M2') {
        this.searchForm.modelThreeNos = [];
        this.searchForm.modelFourNos = [];
      }
      if (level == 'M3') {
        this.searchForm.modelFourNos = [];
      }
      if (level == 'C1') {
        this.searchForm.categoryTwoNos = [];
        this.searchForm.categoryThreeNos = [];
        this.searchForm.categoryFourNos = [];
        this.categoryTwoNosOptions = [];
        this.categoryThreeNosOptions = [];
        this.categoryFourNosOptions = [];
        this.getCategoryDataAction(level, this.filterCategoryUuidList(this.categoryOneNosOptions, e));
      }
      if (level == 'C2') {
        this.searchForm.categoryThreeNos = [];
        this.searchForm.categoryFourNos = [];
        this.categoryThreeNosOptions = [];
        this.categoryFourNosOptions = [];
        this.getCategoryDataAction(level, this.filterCategoryUuidList(this.categoryTwoNosOptions, e));
      }
      if (level == 'C3') {
        this.searchForm.categoryFourNos = [];
        this.categoryFourNosOptions = [];
        this.getCategoryDataAction(level, this.filterCategoryUuidList(this.categoryThreeNosOptions, e));
      }
    },
    // 过滤品类uuid集合
    filterCategoryUuidList (data, categoryNoList) {
      return data.filter(item => categoryNoList.includes(item.categoryNo)).map(item => item.categoryUuid)
    },
    // 格式化模块级联数据
    formatMoudleData (list) {
      const modelData = handleFlatTreeData(list, 'subModels'); // 树形结构扁平化
      this.industryTypeOptions = this.filterMoudleData(
        modelData,
        [0],
        'levelNum'
      );
      this.modelOneNosAllOptions = this.filterMoudleData(
        modelData,
        [1],
        'levelNum'
      );
      this.modelTwoNosAllOptions = this.filterMoudleData(
        modelData,
        [2],
        'levelNum'
      );
      this.modelThreeNosAllOptions = this.filterMoudleData(
        modelData,
        [3],
        'levelNum'
      );
      this.modelFourNosAllOptions = this.filterMoudleData(
        modelData,
        [4],
        'levelNum'
      );
    },
    // 过滤模块数据
    filterMoudleData (list, levels, fileName) {
      return list.filter((item) => levels.includes(item[fileName]));
    },
    // 一级模块参数集合填充
    handleFillModelOneNos () {
      const { industryTypes, modelOneNos } = this.searchForm
      // 当行业类型有值且一级模块无值时，默认查询该行业下的所有一级模块
      if (industryTypes.length && !modelOneNos.length) {
        this.searchForm.modelOneNos = this.modelOneNosOptions.map(item => (item.modelNo))
      }
    },
    // 获取表格数据参数整合
    handleGetTableData (initPageNum) {
      if (initPageNum) {
        this.pagination.pageNum = initPageNum;
      }
      const { pageNum, pageSize } = this.pagination;
      this.handleFillModelOneNos();
      const param = {
        ...this.searchForm,
        pageShow: pageSize,
        nowPage: pageNum
      };
      this.getTableDataAction(param);
    },
    // 导出表格
    handleExport () {
      this.handleFillModelOneNos();
      this.exportLoading = true;
      ApiRequestExportTable('/sysback/product/model/exportProductModelCategoryRelData', 'post', this.searchForm, false).then(res => {
        const blob = new Blob([res], {
          type: 'application/octet-stream'
        });
        var link = document.createElement('a');
        link.href = window.URL.createObjectURL(blob);
        link.download = '模块管理信息.xlsx';
        link.click();
        window.URL.revokeObjectURL(blob); // 释放掉blob对象
        this.exportLoading = false;
      }).catch(() => {
        this.exportLoading = false;
        this.$message.error('导出失败');
      });
    },
    /* 改变页码事件 */
    handlePageChange (currentPage) {
      this.pagination.pageNum = currentPage;
      this.handleGetTableData();
    },
    /* 改变当前页条数大小事件 */
    handlePageSizeChange (pageSize) {
      this.pagination.pageSize = pageSize;
      if (this.tableData.length === 0) {
        return false;
      }
      this.handleGetTableData();
    }
  }
};
</script>
<style lang="less" scoped>
.box-card {
  margin-bottom: 10px;
  .clearfix {
    button {
      float: right;
      margin-left: 8px;
    }
  }
}
</style>
